# -*- coding:utf-8 -*-

# @Time : 2022/11/22 15:11
# @Author : 快乐的小猴子
# @Version : 
# @Function : 

import requests
from lxml import etree
from YouMeiPics.conf import settings
from YouMeiPics.conf.SetProxies import SetProxies


class PublicBases:
    """
    公共类    包含发送请求函数
    """
    def send(self, url):
        '''
        发送请求, 获取响应数据
        :param url:
        :return:
        '''
        # resp = requests.get(url=url, headers=settings.headers, proxies=get_proxy_ip.get_proxy_ip())
        resp = requests.get(url=url, headers=settings.headers, proxies=SetProxies().get_proxies())
        resp.encoding = 'utf-8'
        return resp.text

    def down_pics_send(self, name, url, pics_path):
        '''
        下载单页图片
        :param name:
        :param url:
        :return:
        '''
        try:
            # resp = requests.get(url, headers=settings.headers, proxies=get_proxy_ip.get_proxy_ip())
            resp = requests.get(url=url, headers=settings.headers, proxies=SetProxies().get_proxies())
            with open('{}{}.jpg'.format(pics_path, name), 'wb') as fp:
                fp.write(resp.content)
        except Exception as e:
            print(e)

    def get_son_urls(self, html):
        '''
        获取页面中的下级标题和url地址信息
        :param html:
        :return:
        '''
        et = etree.HTML(html)
        # 二级标题和url
        sec_pic_names = et.xpath('//ul[@class="clearfix"]/li[@class="nav-li  on"]/a/text()')
        sec_pic_urls = et.xpath('//ul[@class="clearfix"]/li[@class="nav-li  on"]/a/@href')
        thr_pic_names = et.xpath('//ul[@class="clearfix"]/li[@class="nav-li  on"]/div[@class="sonnav"]/a/text()')
        thr_pic_urls = et.xpath('//ul[@class="clearfix"]/li[@class="nav-li  on"]/div[@class="sonnav"]/a/@href')
        return sec_pic_names, sec_pic_urls, thr_pic_names, thr_pic_urls

    def handle_son_datas(self, html):
        '''
        处理下级标题和url数据
        :param html:
        :return:
        '''
        sec_pic_names, sec_pic_urls, thr_pic_names, thr_pic_urls = self.get_son_urls(html)
        # 处理二级标题和url
        sec_data_list = []
        for i in range(0, len(sec_pic_names)):
            sec_data_dics = {}
            sec_data_dics[str(i + 1)] = (sec_pic_names[i], settings.url + sec_pic_urls[i])
            sec_data_list.append(('1', sec_data_dics))
        for j in range(0, len(thr_pic_names)):
            thr_data_dics = {}
            thr_data_dics[str(j + 1)] = (thr_pic_names[j], settings.url + thr_pic_urls[j])
            sec_data_list.append(('2', thr_data_dics))
        return sec_data_list